<?php
include('ZReader.php');
include('ZLeadCollection.php');
include('ZLeadItem.php');

class ZLeadReader extends ZReader
{
    protected $cache    = 'lead';

    /**
     * Generate command string
     * @return string
     */
    public function command() {
        return sprintf('leads %d %d %s %s %d %d %s'."\r\n",
            $this->offset,
            $this->limit,
            $this->begin,
            $this->end,
            $this->timeZone,
            $this->language,
            $this->query
        );
    }
    /**
     * Parse data that receive from server to object
     * @param $callback
     * @param $state
     * @return ZLeadCollection
     */
    public function parse($callback, &$state) {
        $i = 0;
        $collections = new ZLeadCollection();

        $arr = array();

        $succeed = false;

        $total      = $this->readNum();
        $collections->setTotal($total);

        //Read data while not end of file
        while (!$this->eof()) {
            //Read the first block is the length of the data
            $numBytes = $this->readNum();

            if ($numBytes >= 0 && $numBytes < 0xffffffff) {
                if ($i  < 7) {
                    $arr[] = $this->readStr($numBytes);
                } else {
                    $arr[] = $this->readNum($numBytes);
                }
                $i++;
                //Enough a item
                if ($i == 10) {
                    $item = new ZLeadItem($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5], $arr[6], $arr[7], $arr[8], $arr[9]);
                    $collections->addItem($item);
                    $arr = array();
                    $i = 0;
                    if (is_callable($callback)) {
                        $callback($item, $total);
                    }
                }
                //Not succeeded
                $succeed = false;
            }
            else if ($numBytes == 0xffffffff) {
                $succeed = true;
            }
        }

        $state = $succeed ? ($collections->count()> 0 ? 1 : 0) : -1;

        return $collections;
    }

    /**
     * Start reading data progress
     * @param null $callback
     * @return ZLeadCollection
     * @throws Exception
     */
    public function read($callback = null) {
        return parent::read($callback);
    }
}

?>